package org.xtframe.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.api.task.Task;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.xtframe.entity.UserData;
import org.xtframe.service.AjaxDataHandler;
import org.xtframe.service.AjaxDataHandlerException;
import org.xtframe.util.ContextUtil;
import org.xtframe.util.JbpmUtil;

@Service
@Scope("prototype")
public class TaskListDataHandler implements AjaxDataHandler {

	private final Log logger = LogFactory.getLog(getClass());

	public Map<String, Object> execute(String strData) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		try {
			UserData userData = ContextUtil.getCurrentUserData();
			if(userData == null){
				map.put(STATUS, false);
				map.put(LOGIN, true);
				throw new AjaxDataHandlerException("未登陆执行获取流程实例列表", 1);
			}
			
			List<Task> taskList = JbpmUtil.getInstance().findPersonalTasks(userData.getUser().getUserId());
			List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
			Map<String, Object> row = null;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			int columnCount = 11;	//预定列的数目
			for (Task task : taskList) {
				row = new HashMap<String, Object>(columnCount);
				row.put("id", task.getId());
				row.put("executionId", task.getExecutionId());
				row.put("name", task.getName());
				row.put("activityName", task.getActivityName());
				row.put("formResourceName", task.getFormResourceName());
				row.put("priority", task.getPriority());
				row.put("duedate", task.getDuedate());
				row.put("assignee", task.getAssignee());
				row.put("progress", task.getProgress());
				row.put("description", task.getDescription());
				row.put("createTime", sdf.format(task.getCreateTime()));
				rows.add(row);
			}
			map.put(STATUS, true);
			map.put(LIST, rows);
		} catch(AjaxDataHandlerException ex){
			logger.warn(ex.toString());
			if(ex.getFlag() == 0){
				map.clear();
				map.put(STATUS, false);
			}
		} catch (Exception e) {
			logger.error(e.toString());
			map.clear();
			map.put(STATUS, false);
		}
		
		return map;
	}

}
